﻿using System;
using Microsoft.Maps.MapControl;

namespace SMIL.Services
{
    public class GWCTileSourceBing : SMILTileSource
    {
        private const string _TILEPATH = @"{GWC_ADDRESS}/service/gmaps?layers={L}&zoom={Z}&x={X}&y={Y}";
        private string _GWCAddress;
        private string _layerName;

        private string[] _cycleString;
        private static int _cycleCount = 0;

        //Constructor Called by XAML instantiation;
        public GWCTileSourceBing()
            : base()
        {
        }

        public GWCTileSourceBing(string GWCAddress, string layerName)
            : this()
        {
            this._GWCAddress = GWCAddress;
            this._layerName = layerName;
            _cycleString = new string[] { "" };
        }

        public GWCTileSourceBing(string GWCAddress, string[] cycleString, string layerName)
            : this(GWCAddress, layerName)
        {
            this._cycleString = cycleString;
        }

        #region TileSource Overrides

        //public override Uri GetUri(int tilePositionX, int tilePositionY, int zoomLevel)
        //{
        //    //int zoom = TileToZoom(tileLevel);
        //    int zoom = zoomLevel;
        //    string url = _TILEPATH;

        //    url = url.Replace("{GWC_ADDRESS}", _GWCAddress);
        //    url = url.Replace("{CYCLE}", _cycleString[_cycleCount]);
        //    url = url.Replace("{L}", _layerName);
        //    url = url.Replace("{Z}", zoom.ToString());
        //    url = url.Replace("{X}", tilePositionX.ToString());
        //    url = url.Replace("{Y}", tilePositionY.ToString());

        //    _cycleCount = (_cycleCount + 1) % _cycleString.Length;

        //    return new Uri(url);
        //}

        public override Uri GetUri(int x, int y, int zoomLevel)
        {
            if (((this.MinZoomLevelSet) && (zoomLevel < MinZoomLevel)) || ((this.MaxZoomLevelSet) && (zoomLevel < MaxZoomLevel)))
                return null;

            string url = _TILEPATH;

            url = url.Replace("{GWC_ADDRESS}", _GWCAddress);
            url = url.Replace("{CYCLE}", _cycleString[_cycleCount]);
            url = url.Replace("{L}", _layerName);
            url = url.Replace("{Z}", zoomLevel.ToString());
            url = url.Replace("{X}", x.ToString());
            url = url.Replace("{Y}", y.ToString());

            _cycleCount = (_cycleCount + 1) % _cycleString.Length;

            return new Uri(url);
        }        

        #endregion

    }
}
